package com.weimob.mcloud.wechatwork.customer.mq.model;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.weimob.mcloud.mcloudratelimitercore.common.RatelimiterInfo;
import com.weimob.mcloud.mcloudratelimitercore.common.enums.LimitKeyEnum;
import com.weimob.mcloud.mcloudratelimitercore.common.utils.LimitKeyUtils;
import com.weimob.mcloud.wechatwork.common.enums.CommonBizErrorEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.request.CustomerGroupListReqDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.CustomerGroupListResBO;
import com.weimob.mcloud.wechatwork.core.adapter.service.ChannelAdapterService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.soa.common.response.SoaResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * @author yuzhaoyang
 * @desc 客户群相关api代理类
 * @date 2021-02-04 17:16
 */
@Service
@Slf4j
public class RemoteChatGroupServiceProxy {

    @Reference
    private PrivateSphereService privateSphereService;

    @Autowired
    ChannelAdapterService channelAdapterService;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;


    /**
     * 如果ownerList为空，从企业微信远程获取corpId下所有群主的所有客户群列表数据。
     * 如果ownerList不为空，所查为corpId下群主ownerList的客户群列表数据。
     * @param ownerList 群主过滤。如果不填，表示获取应用可见范围内全部群主的数据
     *                  （但是不建议这么用，如果可见范围人数超过1000人，为了防止数据包过大，会报错 81017）
     * @return List<ChatId, status>
     */
    public List<CustomerGroupListResBO.GroupChat> getAllCorpGroupChatList(PrivateSphere privateSphere, List<String> ownerList) {
        List<CustomerGroupListResBO.GroupChat> result = new ArrayList<>();
        // 1、check
        if(Objects.isNull(privateSphere)){
            log.error("getAllCorpGroupChatList 查群列表时 私域信息为空");
            return result;
        }

        // 2、滚动从腾讯拉取客户群列表
        String nextCursor = null;
        do {
            SoaResponse<CustomerGroupListResBO, Void> soaResponse = getCustomerGroupList(ownerList, privateSphere, nextCursor);
            CustomerGroupListResBO responseVo = soaResponse.getResponseVo();
            if (CollectionUtils.isEmpty(responseVo.getGroupChatList())) {
                break;
            }
            result.addAll(responseVo.getGroupChatList());
            nextCursor = responseVo.getNextCursor();
        } while (StringUtils.isNotEmpty(nextCursor));

        // 3、返回结果集
        return result;
    }

    private SoaResponse<CustomerGroupListResBO, Void> getCustomerGroupList( List<String> ownerList, PrivateSphere privateSphere, String cursor) {
        log.info("初始化客户群信息、privateSphere:{}", JSON.toJSONString(privateSphere));
        CustomerGroupListReqDTO customerGroupListReqDTO = new CustomerGroupListReqDTO();
        customerGroupListReqDTO.setCorpId(privateSphere.getCorpId());
        customerGroupListReqDTO.setTemplateId(privateSphere.getTemplateId());
        customerGroupListReqDTO.setOwnerList(ownerList);
        customerGroupListReqDTO.setCursor(cursor);
        customerGroupListReqDTO.setProviderIdentity(privateSphere.getChannelProviderIdentity());
        log.info("初始化客户群信息、customerGroupListReqDTO:{}", JSON.toJSONString(customerGroupListReqDTO));
        // adapter 中设定的分页大小为1000
        SoaResponse<CustomerGroupListResBO, Void> soaResponse = channelAdapterService.getGroupChatList(customerGroupListReqDTO);
        String returnCode = soaResponse.getReturnCode();
        CustomerGroupListResBO responseVo = soaResponse.getResponseVo();
        // 接入限频
        if (CommonBizErrorEnum.WECHAT_WORK_LIMIT.getCode().equals(returnCode) || CommonBizErrorEnum.WECHAT_WORK_CONVERT_ID_LIMIT.getCode().equals(returnCode)) {
            if (Objects.nonNull(responseVo)) {
                Long taskId = responseVo.getTaskId();
                log.info("调用腾讯客户群列表接口被限频，taskId:{},msg：{}", taskId, soaResponse.getReturnMsg());
                // 创建一个限频的redis任务记录
                RatelimiterInfo ratelimiterInfo = new RatelimiterInfo(LimitKeyEnum.CUSTOMER_GROUP_LIST_GET.getKey(), JSON.toJSONString(customerGroupListReqDTO));
                redisTemplate.opsForValue().set(LimitKeyUtils.buildRedisKey(taskId), JSON.toJSONString(ratelimiterInfo), 1, TimeUnit.DAYS);
            }
        }
        log.info("初始化客户群信息、chatListResp:{}", JSON.toJSONString(responseVo));
        return soaResponse;
    }

}
